<template>
  <h1 style="margin: 20px">客户基本信息管理</h1>
  <div class="operation_panel">
    <el-button type="primary" :icon="Plus" @click="showAddDialog">添加新数据</el-button>
    <el-button type="danger" :icon="Delete" @click="handleDeleteSelectionRows">删除选中行数据</el-button>
    <!-- 添加搜索框 -->
    <el-input
        v-model="searchQuery"
        placeholder="请输入姓名进行搜索,支持关键词"
        clearable
        style="width: 300px; margin-left: 16px"
        @input="handleSearch"
    >
      <template #prefix>
        <el-icon><search /></el-icon>
      </template>
    </el-input>
  </div>
  <!-- 利用 JavaScript 数组的 slice 方法，根据计算出的起始和结束索引来截取 tableData 中的部分数据 -->
  <el-table :data="tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)" style="width: 100%" border ref="multipleTableRef">
    <el-table-column fixed type="index" label="序号" width="60" />
    <el-table-column fixed type="selection" width="60" />
    <el-table-column fixed prop="patientId" label="Id" width="80" />
    <el-table-column prop="name" label="姓名" />
    <el-table-column prop="age" label="年龄" width="120" />
    <el-table-column prop="sex" label="性别" width="120" />
    <el-table-column prop="contactNumber" label="联系电话" width="120" />
    <el-table-column fixed="right" label="操作" width="150">
      <template #default="scope">
        <el-button
            size="small"
            type="primary"
            @click="showEditDialog(scope.$index, scope.row)"
        >
          Edit
        </el-button>
        <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
        >
          Delete
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 表尾 -->
  <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[20, 40, 60, 80, 100]"
      background
      layout="prev, pager, next, jumper, total, sizes"
      :total="tableData.length"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />
  <!-- 添加新数据对话框 -->
  <!-- 模态框 -->
  <el-dialog v-model="dialogFormVisible" title="言㐱陪诊" width="500">
    <el-form :model="form" :rules="rules" ref="formRef" label-position="right" label-width="auto">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input v-model.number="form.age" autocomplete="off" />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-input v-model="form.sex" autocomplete="off" />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactNumber">
        <el-input v-model="form.contactNumber" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="!isEdit" type="primary" @click="handleAdd">新增</el-button>
        <el-button v-else type="primary" @click="handleEdit">修改</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { Delete, Plus } from "@element-plus/icons-vue";
import axios from "axios";
import { ElMessage } from "element-plus";

export default {
  components: { Delete, Plus },
  data() {
    return {
      currentPage: 1,
      pageSize: 20,
      dialogFormVisible: false,
      isEdit: false,
      tableData: [], // 表格数据
      searchQuery: "", // 搜索框内容
      form: {
        name: '',
        age: 0,
        sex: '',
        contactNumber: '',
      },
      rules: {
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ],
        age: [
          {required: true, message: '请输入年龄', trigger: 'blur'},
          {type: 'number', message: '年龄必须为数字值', trigger: 'blur'}
        ],
        sex: [
          {required: true, message: '请输入性别', trigger: 'blur'}
        ],
        contactNumber: [
          {required: true, message: '请输入联系电话', trigger: 'blur'}
        ]
      }
    };
  },
  created() {
    this.getTableData();
  },
  methods: {
    // 处理搜索
    async handleSearch() {
      if (this.searchQuery.trim() === "") {
        this.getTableData(); // 如果搜索框为空，重新加载所有数据
        return;
      }
      try {
        const res = await axios.get(`/api/wu_vue_2_test/Patient/SelectByName?name=${this.searchQuery}`);
        if (res.data.data.length === 0) {
          ElMessage({
            message: "未查询到该名字",
            type: "warning",
            plain: true,
          });
        }
        this.tableData = res.data.data; // 更新表格数据
      } catch (error) {
        console.error("搜索失败:", error);
        ElMessage({
          message: "搜索失败，请稍后重试",
          type: "error",
          plain: true,
        });
      }
    },
    // 1. 获取所有数据
    async getTableData() {
      try {
        const res = await axios.get('/api/wu_vue_2_test/Patient/get');
        console.log(res.data);
        this.tableData = res.data.data;
      } catch (error) {
        console.error('获取数据失败:', error);
        ElMessage({
          message: '获取数据失败，请稍后重试',
          type: 'error',
          plain: true
        });
      }
    },
    // 2. 添加新数据
    async handleAdd() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            console.log(this.form);
            const res = await axios.post('/api/wu_vue_2_test/Patient/add', this.form);
            console.log(res);
            this.dialogFormVisible = false;
            await this.getTableData();
            this.showMsg(res);
          } catch (error) {
            console.error('添加数据失败,被占用或网络不佳:', error);
            ElMessage({
              message: '添加数据失败,被占用或网络不佳，请稍后重试',
              type: 'error',
              plain: true
            });
          }
        } else {
          console.log('表单验证不通过');
          return false;
        }
      });
    },
    // 3. 删除当前行数据
    async handleDelete(index, row) {
      try {
        const res = await axios.post('/api/wu_vue_2_test/Patient/del', row);
        await this.getTableData();
        this.showMsg(res);
      } catch (error) {
        console.error('删除数据失败:', error);
        ElMessage({
          message: '删除数据失败，请稍后重试',
          type: 'error',
          plain: true
        });
      }
    },
    // 4. 修改当前行数据
    async handleEdit() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            const res = await axios.post('/api/wu_vue_2_test/Patient/update', this.form);
            this.dialogFormVisible = false;
            await this.getTableData();
            this.showMsg(res);
          } catch (error) {
            console.error('修改数据失败,被占用或网络不佳:', error);
            ElMessage({
              message: '修改数据失败,被占用或网络不佳，请稍后重试',
              type: 'error',
              plain: true
            });
          }
        } else {
          console.log('表单验证不通过');
          return false;
        }
      });
    },
    // 5. 删除选中行数据
    async handleDeleteList(selectedRows) {
      try {
        const res = await axios.post('/api/wu_vue_2_test/Patient/delList', selectedRows);
        await this.getTableData();
        this.showMsg(res);
      } catch (error) {
        console.error('批量删除数据失败:', error);
        ElMessage({
          message: '批量删除数据失败，请稍后重试',
          type: 'error',
          plain: true
        });
      }
    },
    // 删除选中行数据（批量删除）
    handleDeleteSelectionRows() {
      const selectedRows = this.$refs.multipleTableRef.getSelectionRows();
      console.log(selectedRows);
      this.handleDeleteList(selectedRows);
    },
    // 分页事件处理方法
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      console.log('handleSizeChange', this.pageSize);
    },
    // 分页事件处理方法
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      console.log('handleCurrentChange', this.currentPage);
    },
    // 显示添加新数据对话框
    showAddDialog() {
      this.isEdit = false;
      this.dialogFormVisible = true;
      this.resetForm();
    },
    // 显示编辑对话框
    showEditDialog(index, row) {
      console.log(index, row);
      this.dialogFormVisible = true;
      this.isEdit = true;
      this.form = {...row};
    },
    // 重置表单
    resetForm() {
      this.form = {
        name: '',
        age: 0,
        sex: '',
        contactNumber: ''
      };
    },
    // 显示操作结果消息
    showMsg(res) {
      if (res.data.code === 200) {
        ElMessage({
          message: res.data.msg,
          type: 'success',
          plain: true
        });
      } else {
        ElMessage({
          message: res.data.msg,
          type: 'error',
          plain: true
        });
      }
    }
  }
};
</script>

<style scoped>
h1 {
  color: #191919;
}

.operation_panel {
  margin-bottom: 16px;
}

.el-pagination {
  margin-top: 16px;
}
</style>